<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;

/**系统派单
 * Class AutomaticDispatch
 * @package app\command
 */
class AutomaticDispatch extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('automaticdispatch')
            ->setDescription('the automaticdispatch command');
    }

    protected function execute(Input $input, Output $output)
    {
        $start = microtime(true);
        try {
//            $start = microtime(true);
            $time = time();
            $map [] = ['status', '=', 1];
            $map [] = ['is_pay', '=', 1];
            $map [] = ['regus_time', '<', $time];
//            $page = 1;
            $limit = 10000;
            while (true) {
                $operate = [];
                $order = [];
                $info = Db::table('eb_order')
                    ->field('id,operate_id')
                    ->where($map)->page(1, $limit)->select()->toArray();
                if (!$info) break;
                foreach ($info as $v) {
//                    // 获取最少接单的专业骑手id
                    if (!isset($operate[$v['operate_id']])) {
                        $data = Cache::store('redis')->handler()->zRange('operate-' . $v['operate_id'], 0, -1, true);
                        array_fill_keys(array_keys($data),0);
                        $operate[$v['operate_id']] = array_fill_keys(array_keys($data),0);
                    }
//                    // 将最小的+1
                    $senderId = key($operate[$v['operate_id']]);
                    $num = current($operate[$v['operate_id']]);
                    $operate[$v['operate_id']][$senderId] = ++ $num;
                    asort($operate[$v['operate_id']]);
                    $order[$senderId][] = $v['id'];
                }
                // 修改订单
                foreach ($order as $sender => $ids) {
                    Db::table('eb_order')->where('id', 'in', $ids)->update([
                        'send_id' => $sender,
                        'receipt_time' => $time,
                        'status' => 2
                    ]);
                }
                foreach ($operate as $operateId => $sernderInfo) {
                    foreach ($sernderInfo as $newId => $inc) {
                        if ($inc == 0) continue;
                        Cache::store('redis')->handler()->zIncrBy('operate-' . $operateId, $inc, $newId);
                    }
                }
            }
            var_dump(microtime(true) - $start);
        } catch (\Exception $e) {
//            var_dump($e->getMessage());
            exit;
        }
    }
}
